<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Project;
use App\Models\AdminUser;
use App\Models\Contract;
use App\Models\ProSource;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Widgets\Markdown;

class ProjectController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Project(['projectusers', 'saleusers', 'prosource', 'customer', 'technicalstaffs']), function (Grid $grid) {
            if (!Admin::user()->inRoles(['administrator', 'sale_admin', 'sales_executive'])) {
                $grid->model()->where('user_id', Admin::user()->id);
            }
            $grid->column('id')->sortable();
            $grid->column('name');
            $grid->column('desc')->display('查看')->modal(function ($modal) {
                $modal->title('ID:' . $modal->row->id . '的内容');
                return new Markdown($modal->row->desc);
            });
            $grid->column('amount');
            $grid->column('projectusers.alias_name', '项目负责人');
            $grid->column('saleusers.alias_name', '销售代表');
            $grid->column('budget');
            $grid->column('customer.name', '客户');
            $grid->column('status')->using([0 => '洽谈中', 1 => '签订合同，未付款', 2 => '签订合同，已付款', 3 => '开发中', 4 => '开发完成', 5 => '完成']);
            $grid->column('schedule')->progressBar('success', 'sm', 100);
            $grid->column('technicalstaffs.alias_name', '技术人员');
            $grid->column('prosource.name', '来源');
            $grid->column('construction_period');
            $grid->column('balance_payment');
            $grid->column('project_cost');
            $grid->column('gross_profit');
            $grid->column('contract_no')->if(function ($column) {
                return empty($column->getValue());
            })->display(function ($value) {
                return '暂无合同';
            })->else()->display('查看合同')->modal(function ($modal) {
                $con = Contract::where('id', $modal->row->contract_no)->first();
                $modal->title('项目编号:' . $modal->row->id . '-合同编号【' . $con->code . '】');
                return new Markdown($con->content);
            });;
            $grid->column('remark')->display('查看') // 设置按钮名称
            ->modal(function ($modal) {
                $modal->title('ID:' . $modal->row->id . '的内容');
                return new Markdown($modal->row->remark);
            });
            $grid->column('admin_id')->display(function ($value) {
                return AdminUser::where('id', $value)->value('name');
            });
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
            if (!Admin::user()->inRoles(['administrator', 'sale_admin', 'sales_executive'])) {
                $grid->disableCreateButton();
                $grid->disableEditButton();
                $grid->disableDeleteButton();
            }
            $grid->selector(function (Grid\Tools\Selector $selector) {
                $selector->select('status', '状态', [0 => '洽谈中', 1 => '签订合同，未付款', 2 => '签订合同，已付款', 3 => '开发中', 4 => '开发完成', 5 => '完成']);
            });
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Project(), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('desc');
            $show->field('amount');
            $show->field('prouser');
            $show->field('user_id');
            $show->field('budget');
            $show->field('customer_id');
            $show->field('status');
            $show->field('schedule');
            $show->field('technical_staff');
            $show->field('source');
            $show->field('construction_period');
            $show->field('balance_payment');
            $show->field('project_cost');
            $show->field('gross_profit');
            $show->field('contract_no');
            $show->field('remark');
            $show->field('admin_id');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Project(), function (Form $form) {
            $form->display('id');
            $form->tab('项目信息', function (Form $form) {
                $form->text('name')->required();
                $form->editor('desc', '项目内容');//内容
                $form->select('prouser')->options(function () {
                    $user = new AdminUser();
                    $users = $user->alluser(['sales_executive']);
                    return $users->pluck('alias_name', 'id');
                });//项目负责人
                $form->select('user_id')->options(function () {
                    $user = new AdminUser();
                    $users = $user->alluser('salesperson');
                    return $users->pluck('alias_name', 'id');
                });//销售代表

                $form->radio('status', '状态')
                    ->options([0 => '洽谈中', 1 => '签订合同，未付款', 2 => '签订合同，已付款', 3 => '开发中', 4 => '开发完成', 5 => '完成'])
                    ->default(0);//状态
                $form->select('source')->options(ProSource::all()->pluck('name', 'id'));//来源
                $form->currency('amount')->symbol('元');//成交金额
                $form->currency('construction_period')->symbol('天')->placeholder('请输入天数');//工期
                $form->currency('balance_payment')->symbol('元');//尾款
                $form->currency('project_cost')->symbol('元');//项目成本
                $form->currency('gross_profit')->symbol('元');//毛利润

                $form->textarea('remark');//备注
                $form->hidden('admin_id')->default(auth('admin')->user()->id);//创建人

                $form->datetime('created_at')->required();
                $form->display('updated_at');
            });
            $form->tab('客户信息', function (Form $form) {
                $form->radio('customer_radio', '客户选择')
                    ->when(1, function (Form $form) {
                        $form->select('customer_id', '客户')->options(function () {
                            $customer = \App\Models\Customer::all();
                            return $customer->pluck('name', 'id');
                        });//客户
                    })
                    ->when(2, function (Form $form) {
                        $form->text('cus_name', '客户称呼');
                        $form->mobile('phone', '手机号');
                        $form->email('email', '邮件');
                        $form->distpicker([
                            'province_name' => '省份',
                            'city_name' => '市',
                            'district_name' => '区'
                        ], '地域选择')->type('code');
                        $form->text('address', '详细地址');
                        $form->radio('sex', '性别')->options([1 => '男', 0 => '女']);
                        $form->select('identity', '身份')->options(\App\Models\Customer::$identity);
                        $form->select('cus_source', '来源')->options(ProSource::all()->pluck('name', 'id'));//来源
                        if (Admin::user()->inRoles(['administrator', 'sale_admin'])) {
                            $form->select('user_id2', '销售人员')->options(\App\Models\AdminUser::all()->pluck('name', 'id'))->help('管理员可修改');
                        } else {
                            $form->hidden('user_id2')->value(Admin::user()->id);

                        }
                        $form->textarea('desc', '备注')->help('可以在这里添加其他联系方式或者备注');
                    })
                    ->options([1 => '手工选择', 2 => '手工填写'])
                    ->default(1)->required();
                $form->currency('budget', '客户预算')->symbol('元');//客户预算
            });
            $form->tab('技术信息', function (Form $form) {
                $form->select('technical_staff')->options(function () {
                    $user = new AdminUser();
                    $users = $user->alluser('developer');
                    return $users->pluck('alias_name', 'id');
                });//技术人员
            });
            $form->tab('合同信息', function (Form $form) {
                $form->select('contract_no')->options(Contract::all()->pluck('code', 'id'));//合同编号
            });


        })->saving(function (Form $form) {
            $status = $form->input('status');
            $form->schedule = \App\Models\Project::$statusToSchedule[$status];


            if ($form->customer_radio == 2) {//处理新增客户信息
                $customer = new \App\Models\Customer();
                $customer->name = $form->cus_name;
                $customer->phone = $form->phone;
                $customer->email = $form->email;
                $customer->province_name = $form->province_name;
                $customer->city_name = $form->city_name;
                $customer->district_name = $form->district_name;
                $customer->address = $form->address;
                $customer->sex = $form->sex;
                $customer->identity = $form->identity;
                $customer->user_id = $form->user_id2;
                $customer->desc = $form->desc;
                $customer->source = $form->cus_source;
                if ($customer->save()) {
                    $form->customer_id = $customer->id;
                } else {
                    return $form->response()->error('客户信息保存失败');
                }
            }
            $form->deleteInput(['cus_name', 'phone', 'email', 'province_name', 'city_name', 'district_name', 'address', 'sex', 'identity', 'cus_source', 'desc', 'customer_radio', 'user_id2']);

        });
    }
}
